package cn.itsource.pethome.user.service.impl;

import cn.itsource.pethome.basic.util.HttpClientUtils;
import cn.itsource.pethome.basic.util.MD5Utils;
import cn.itsource.pethome.basic.util.RedisUtils;
import cn.itsource.pethome.basic.util.StrUtils;
import cn.itsource.pethome.user.constant.PhoneConstant;
import cn.itsource.pethome.user.constant.WechatConstant;
import cn.itsource.pethome.user.domain.User;
import cn.itsource.pethome.user.domain.WechatUser;
import cn.itsource.pethome.user.domain.dto.WechatUserDto;
import cn.itsource.pethome.user.mapper.UserMapper;
import cn.itsource.pethome.user.mapper.WechatMapper;
import cn.itsource.pethome.user.service.IWechatService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @description: 描述:
 * @date: 2020/8/17 19:14
 * @author: summer
 * version: 1.0
 */
@Service
public class WechatServiceImpl implements IWechatService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WechatMapper wechatMapper;

    @Override
    public Map<String, Object> getToken(String code) {
        //token的地址
        String tokenUrl = WechatConstant.ACCESS_TOKEN.replace("APPID", WechatConstant.APPID)
                .replace("SECRET", WechatConstant.SECRET)
                .replace("CODE", code);
        //发送get请求
        String httpGet = HttpClientUtils.httpGet(tokenUrl);
        //System.out.println(httpGet);
        //把json字符串转为对象
        JSONObject jsonObject = JSON.parseObject(httpGet);
        //System.out.println(jsonObject);
        //获取token值
        String access_token = jsonObject.getString("access_token");
        //获取用户唯一标识
        String openid = jsonObject.getString("openid");
        //获取微信用户url
        String userInfoUrl = WechatConstant.USERINFO_URL.replace("ACCESS_TOKEN", access_token)
                .replace("OPENID", openid);
        //获取用户信息
        String userInfoJson = HttpClientUtils.httpGet(userInfoUrl);
        //把json字符转为对象
        JSONObject userInfo = JSON.parseObject(userInfoJson);
        System.out.println("用户信息；"+userInfo);
        //通过openid查询用户是否已存在
        WechatUser wechatUser = wechatMapper.loadByOpenid(openid);
        Map<String, Object> map = new HashMap<>();
        //查询为空，表名第一次登陆
        if(wechatUser==null){
            WechatUser user = new WechatUser();
            //取出地址
            String country = userInfo.getString("country");
            String province = userInfo.getString("province");
            String city = userInfo.getString("city");
            //设置地址
            user.setAddress(country+province+city);
            user.setHeadimgurl(userInfo.getString("headimgurl"));//设置头像
            user.setNickname(userInfo.getString("nickname"));    //设置昵称
            user.setOpenid(openid);                                  //用户唯一标识符
            user.setSex(userInfo.getInteger("sex"));             //性别
            user.setUnionid(userInfo.getString("unionid"));      //用户统一标识
            //添加微信用户信息
            wechatMapper.save(user);
            //转跳到绑定页面
            map.put("url", WechatConstant.REDIRECT_SERVER+WechatConstant.BINDING+"?openid="+openid);
            return map;
        }else {//微信用户第一次扫描，但是没有绑定账户
            User user = wechatUser.getUser();
            //user为空，证明没有绑定用户名和密码的
            if(user==null){
                //转跳到绑定页面
                map.put("url", WechatConstant.REDIRECT_SERVER+WechatConstant.BINDING+"?openid="+wechatUser.getOpenid());
                return map;
            }
            //user不为空 已经绑定，直接跳转主页，并返回用户名密码
            String token = UUID.randomUUID().toString();
            RedisUtils.INSTANCE.set(token, JSON.toJSONString(user),30*60 );
            map.put("token",token );
            map.put("loginUser", user);
            return map;
        }
    }

    /**
     * 功能描述: 获取绑定页面信息绑定微信用户
     * @param wechatUserDto
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @Date: 2020/8/18
     */
    @Override
    public Map<String, Object> binding(WechatUserDto wechatUserDto) {
        //获取用户名
        String username = wechatUserDto.getUsername();
        //查询是否有user
        User user = userMapper.loadByPhone(username);
        Map<String, Object> map = new HashMap<>();
        //没有就创建
        if(user == null){
            User u = new User();
            u.setUsername(wechatUserDto.getUsername());
            String salt = StrUtils.getComplexRandomString(10);
            u.setSalt(salt);
            u.setPassword(MD5Utils.encrypByMd5(wechatUserDto.getPassword()+salt));
            u.setState(PhoneConstant.ACTIVATE);
            //保存用户
            userMapper.save(u);
            //把微信用户信息和注册本产品用户信息绑定
            wechatMapper.binding(u.getId(),wechatUserDto.getOpenid());
            String token = UUID.randomUUID().toString();
            //把信息存到redis中   会话
            RedisUtils.INSTANCE.set(token, JSON.toJSONString(u),30*60 );
            map.put("token",token );
            map.put("loginUser", u);
            return map;
        }
        //用户名正确 验证密码
        if(!user.getPassword().equals(MD5Utils.encrypByMd5(wechatUserDto.getPassword()+user.getSalt()))){
            throw new RuntimeException("密码错误");
        }
        //绑定
        wechatMapper.binding(user.getId(),wechatUserDto.getOpenid());
        //token
        String token = UUID.randomUUID().toString();
        //把账户密码设置进redis 会话
        RedisUtils.INSTANCE.set(token, JSON.toJSONString(user),30*60 );
        map.put("token",token );
        map.put("loginUser", user);
        return map;
    }
}
